package com.lucy.flow.module.transition.listener;

import com.lucy.flow.domain.entity.FlowWork;
import com.lucy.flow.event.FlowWorkDeletedEvent;
import com.lucy.flow.module.transition.FlowTransition;
import com.lucy.flow.module.transition.FlowTransitionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author kindear
 * 流程实例相关事件监听
 */
@Slf4j
@Service
public class FlowWorkListener {
    @Autowired
    FlowTransitionService transitionService;

    @EventListener(FlowWorkDeletedEvent.class)
    public void flowWorkDeletedEvent(FlowWorkDeletedEvent event){
        FlowWork flowWork = event.getFlowWork();
        FlowTransition transition = new FlowTransition();
        transition.setFlowWorkId(flowWork.getId());
        Example<FlowTransition> example = Example.of(transition);
        List<FlowTransition> transitions = transitionService.getExample(example);
        List<String> idList = transitions.stream().map(FlowTransition::getId).collect(Collectors.toList());
        transitionService.batchDelete(idList);
        log.debug("流程实例:ID:{};name:{} 关联流转记录删除完成",flowWork.getId(),flowWork.getFlowName());
    }
}
